﻿using Adp;
using Adp.Common;
using Microsoft.AspNetCore.Mvc;
using Yqd.Models;
using System;
using System.Linq;
using Yqd.Enm;
using Yqd.Core;
using Yqd.Controllers.Filter;
using Newtonsoft.Json.Linq;
using Adp.Models;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Newtonsoft.Json;
using Yqd.Dto;

namespace Yqd.Controllers
{
    [Area("Yqd")]
    public class WxUserController : Controller
    {
        TcmContext tcm;
        YqdContext ctx;
        DdService ddService;
        int count = 0;
        static string UnitCode = "";
        static string UnitName = "";

        public WxUserController(TcmContext tcm, YqdContext ctx, DdService ddService)
        {
            this.tcm = tcm;
            this.ctx = ctx;
            this.ddService = ddService;
        }

        public ActionResult Login()
        {
            var code = Form.GetString("auth_code");
            if (code.Trim() == "") code = Form.GetString("code");
            var EmployeeCode = Form.GetString("EmployeeCode", "GE_a6dabcc3edce4ebea9775dfa26ed99ed");
            YqdUser user = null;
            if (code.HasValue())
            {
                //user = ddService.GetAppUser(code);
                EmployeeCode = ddService.GetAppUser(code);
            }

            if (EmployeeCode.HasValue())
            {
                var su = ctx.Yqd_User.FirstOrDefault(it => it.EmployeeCode == EmployeeCode && it.Status == 用户状态.使用中);
                if (su != null)
                {
                    var unit = GetUnit(su.UnitCode);
                    var unitInfo = ctx.Yqd_Unit.Where(x => x.OrganizationCode == unit.UnitCode).FirstOrDefault();
                    if (unitInfo != null)
                    {
                        UnitCode = unitInfo.UnitCode;
                        UnitName = unitInfo.Name;
                    }

                    //var unit = ctx.Yqd_Unit.FirstOrDefault(it => it.OrganizationCode == su.UnitCode);
                    //string UnitCode = "", UnitName = "";
                    //if (unit != null)
                    //{
                    //    UnitCode = unit.UnitCode;
                    //    UnitName = unit.Name;
                    //}
                    user = new YqdUser
                    {
                        Role = new List<角色类型>(),
                        Permit = new List<权限清单>(),
                        Avatar = su.Avatar,
                        Name = su.Name,
                        AccountId = su.AccountId,
                        UnitCode = UnitCode,
                        UnitName = UnitName,
                        OrganizationCode = su.UnitCode,
                        EmployeeCode = su.EmployeeCode
                    };
                    if (!string.IsNullOrWhiteSpace(su.Roles))
                    {
                        user.Role = su.Roles.Split(",").Select(it => (角色类型)int.Parse(it)).ToList();
                    }
                    if (!string.IsNullOrWhiteSpace(su.PermitItem))
                    {
                        user.Permit = su.PermitItem.Split(",").Select(it => (权限清单)int.Parse(it)).ToList();
                    }
                }
            }
            if (user != null)
            {
                if (user.Role.Any(it => it > 角色类型.未设置 && it < 角色类型.协调人))
                {
                    LoggingService.AddLog(user.EmployeeCode);
                    user.Dev = Form.GetInt("Dev");
                    WxUser.LoginMini(user);
                    var taskID = Form.GetLong("TaskID", -1);
                    var url = "";
                    if (taskID > -1)
                    {
                        if (taskID == 0) url = "/tip?dev=" + user.Dev;
                        else
                        {
                            var dd = Form.GetInt("dd", 0);
                            if (dd > 0) url = "/dcd#/supervision/supervisionDetail?TaskID=" + taskID.ToString();
                            else
                            {
                                url = "/zld#/phoneDing/dingDetail?TaskID=" + taskID.ToString();
                                var superID = Form.GetInt("superID", 0);
                                if (superID > 0)
                                {
                                    ctx.Database.ExecuteSql("update Yqd_Supervise set IsRead=1 where SuperviseID={0};", superID);
                                }
                            }
                        }
                    }
                    else
                    {
                        url = WxUser.RedirectUrl;
                    }

                    //var rootPath = Env.ServerRoot.Combine("wwwroot");
                    //FileHelper.RecordLogs(rootPath + "/logtail.txt", "{\"appCode\":\"A330782384504202109000002\",\"userId\": \"" + user.EmployeeCode + "\", \"userRole\": \"政府人员\", \"areaCode\": \"330700\", \"actionType\": 1, \"actionId\": \"90548\", \"actionTime\": \"" + DateTime.Now + "\", \"actionDuration\": 995, \"actionStatus\": 0}");

                    if (url != "")
                    {
                        return this.ToJson(new
                        {
                            success = true,
                            code,
                            dev = user.Dev,
                            url
                        });
                    }
                }
            }
            return this.ToJson(new
            {
                success = false,
                code
            });
        }

        [User(false)]
        public ActionResult GetUser()
        {
            var user = WxUser.LogonInfo;
            var Avatar = "";
            if (!string.IsNullOrWhiteSpace(user.Avatar))
            {
                var rootPath = Env.ServerRoot.Combine("wwwroot");
                var filepath = "/Client/Yqd/Avatar/";
                var path = rootPath + filepath;
                if (!Directory.Exists(path)) Directory.CreateDirectory(path);
                var filename = user.EmployeeCode + ".jpg";
                path += filename;
                if (!System.IO.File.Exists(path))
                {
                    ddService.GenerateAvatar(user.Avatar, path);
                }
                Avatar = filepath + filename;
            }
            var userinfo = ctx.Yqd_User.Where(x => x.EmployeeCode == user.EmployeeCode).Select(x => new { x.UnitName, x.UnitCode }).FirstOrDefault();
            var unit = GetUnit(userinfo.UnitCode);
            var unitInfo = ctx.Yqd_Unit.Where(x => x.OrganizationCode == unit.UnitCode).FirstOrDefault();
            user.UnitCode = unit.UnitCode;
            if (unitInfo != null)
            {
                user.UnitName = unitInfo.Name;
            }
            return this.ToJson(new
            {
                success = true,
                user.EmployeeCode,
                user.Role,
                Avatar,
                user.Name,
                user.UnitCode,
                user.UnitName,
                user.OrganizationCode,
                user.Dev,
                WxUser.Platform
            });
        }

        [User(false)]
        public ActionResult GetPlatform()
        {
            return this.ToJson(new
            {
                success = true,
                WxUser.Platform
            });
        }

        public ActionResult GetAccountID()
        {
            var code = Form.GetString("auth_code");
            var AccountId = "";
            if (code.HasValue())
            {
                var EmployeeCode = ddService.GetAppUser(code);
                var user = ctx.Yqd_User.FirstOrDefault(it => it.EmployeeCode == EmployeeCode && it.Status == 用户状态.使用中);

                if (user != null) AccountId = user.AccountId.ToString();
            }

            return this.ToJson(new
            {
                success = true,
                AccountId
            });
        }

        [User]
        public ActionResult GetDcRole()
        {
            var role = WxUser.LogonInfo.Role;
            return this.ToJson(new
            {
                success = true,
                IsDcry = role.Any(it => it == 角色类型.管理员 || it == 角色类型.督查人员),
                IsDcgl = role.Any(it => it == 角色类型.督查管理员),
                IsDcy = role.Any(it => it == 角色类型.督查员)
            });
        }

        public ActionResult LoginOut()
        {
            WxUser.LoginOut();
            return this.ToJson(new
            {
                success = true
            });
        }

        [User]
        public ActionResult GetOrgUser()
        {
            var level = Form.GetInt("Level", 0);
            var ShowUser = Form.GetBool("ShowUser", false);
            var OrgCode = Form.GetString("OrgCode");
            if (level == 0)
            {
                var data = new List<object>();
                if (string.IsNullOrWhiteSpace(OrgCode)) OrgCode = WxUser.LogonInfo.OrganizationCode;
                else
                {
                    var unit = ctx.Yqd_Unit.FirstOrDefault(it => it.UnitCode == OrgCode);
                    if (unit != null) OrgCode = unit.OrganizationCode;
                }
                var d = ctx.Yqd_Department.FirstOrDefault(it => it.OrganizationCode == OrgCode);
                if (d != null)
                {
                    data.Add(new
                    {
                        d.OrganizationCode,
                        label = d.Name,
                        Level = 1,
                        ShowUser = false,
                        d.isLeaf
                    });
                }
                return this.ToJson(new
                {
                    success = true,
                    data
                });
            }
            if (ShowUser)
            {
                var config = Config.AppSecret(AccessTokenMode.浙政钉通讯录);
                var userList = ddService.pageOrganizationEmployeePositions(OrgCode, config.TenantId);
                var arr = new List<EmployeeDto>();
                if (userList != null)
                {
                    foreach (var o in userList)
                    {
                        var it = JToken.Parse(o.ToString());
                        var Name = it["employeeName"]?.ToString() ?? "";
                        if (arr.Any(m => m.label == Name)) continue;
                        if (it["status"].ToString() == "F") continue;

                        var oCode = it["govEmployeePositions"][0]["organizationCode"]?.ToString();
                        arr.Add(new EmployeeDto
                        {
                            OrganizationCode = oCode,
                            EmployeeCode = it["employeeCode"]?.ToString() ?? "",
                            label = it["employeeName"]?.ToString() ?? "",
                            posOrder = Convert.ToInt32(it["govEmployeePositions"][0]["orderInOrganization"]?.ToString()),
                            Level = 3,
                            ShowUser = false,
                            isLeaf = true,
                            gmtCreate = Convert.ToDateTime(it["gmtCreate"].ToString()),
                            empGender = Convert.ToInt32(it["empGender"].ToString())
                        });
                    }
                    arr = arr.OrderBy(it => it.posOrder).ThenBy(it => it.empGender).ThenBy(it => it.gmtCreate).ToList();
                    var listEmployee = arr.Any() ? arr.Select(x => x.EmployeeCode).ToList() : new List<string>();
                    var listUserUnit = ctx.Yqd_User.Where(x => !listEmployee.Contains(x.EmployeeCode) && x.UnitCode == OrgCode && x.Status == 用户状态.使用中 && x.IsUpdateUnit == 1).ToList();
                    if (listUserUnit.Any())
                    {
                        foreach (var item in listUserUnit)
                        {
                            arr.Add(new EmployeeDto
                            {
                                OrganizationCode = item.OrganizationCode,
                                EmployeeCode = item.EmployeeCode,
                                label = item.Name,
                                posOrder = item.orderInOrganization.ToInt(),
                                Level = 3,
                                ShowUser = false,
                                isLeaf = true,
                                gmtCreate = Convert.ToDateTime(item.gmtCreate),
                                empGender = item.Gender
                            });
                        }
                    }
                }
                //string json = JsonConvert.SerializeObject(arr.OrderBy(it => it.posOrder).ThenBy(it => it.empGender).ThenBy(it => it.gmtCreate).ToList());
                //var r = ctx.Yqd_User.Where(it => it.OrganizationCode == OrgCode);
                return this.ToJson(new
                {
                    success = true,
                    data = arr
                });
            }
            var dept = ctx.Yqd_Department.Where(it => it.ParentCode == OrgCode);
            return this.ToJson(new
            {
                success = true,
                data = dept.ToList().Select(it => new
                {
                    it.OrganizationCode,
                    label = it.Name,
                    Level = 2,
                    ShowUser = it.isLeaf,
                    isLeaf = false
                })
            });
        }

        public ActionResult GetUnitUser()
        {
            var UnitCode = Form.GetString("UnitCode", "GO_c057f9a4cb06442d9d6480c377810454");
            var users = ctx.Yqd_User.Where(it => it.UnitCode == UnitCode);
            return this.ToJson(new
            {
                success = true,
                data = users.Select(it => new
                {
                    it.EmployeeCode,
                    it.Name,
                    it.AccountId,
                    it.Avatar,
                    it.OrganizationCode,
                    it.OrganizationName,
                    it.empBudgetedPostName
                })
            });
        }

        public ActionResult UpdateLevel()
        {
            var config = Config.AppSecret(AccessTokenMode.浙政钉通讯录);
            UpdateConfig("单位级别", ddService.queryByPropertyCode("govInstitutionLevel", config.TenantId));
            UpdateConfig("人员编制", ddService.queryByPropertyCode("govEmpBudgetedPost", config.TenantId));
            UpdateConfig("职级", ddService.queryByPropertyCode("govEmpJobLevel", config.TenantId));
            UpdateConfig("性别", ddService.queryByPropertyCode("govEmpGender", config.TenantId));
            UpdateConfig("政治面貌", ddService.queryByPropertyCode("govEmpPoliticalStatus", config.TenantId));
            UpdateConfig("任职类型", ddService.queryByPropertyCode("govJobAttributes", config.TenantId));
            UpdateConfig("人员角色", ddService.queryByPropertyCode("govEmpPosEmployeeRole", config.TenantId));
            UpdateConfig("职务层次", ddService.queryByPropertyCode("govEmpJobRank", config.TenantId));
            UpdateConfig("可见性标识", ddService.queryByPropertyCode("visibilityIndicator", config.TenantId));

            return this.ToJson(new
            {
                success = true
            });
        }
        public ActionResult UpdateAllDepartment()
        {
            var config = Config.AppSecret(AccessTokenMode.浙政钉通讯录);
            var sc = ddService.scopesV2(config.TenantId);
            var arr = new List<string>();
            foreach (var item in sc["deptVisibleScopes"])
            {
                LoadDepartment(item.ToString(), config.TenantId, arr);
            }
            if (arr.Any())
            {
                var xx = "";
            }
            return this.ToJson(new
            {
                success = true
            });
        }
        public ActionResult UpdateAllUser()
        {
            var config = Config.AppSecret(AccessTokenMode.浙政钉通讯录);
            var users = ctx.Yqd_User.ToList();
            List<string> listEmployee = new List<string>();
            var departments = ctx.Yqd_Department.ToList();
            foreach (var d in departments)
            {
                var userList = ddService.pageOrganizationEmployeePositions(d.OrganizationCode, config.TenantId);
                if (userList != null)
                {
                    int count = userList.Count;
                    foreach (var o in userList)
                    {
                        var it = JToken.Parse(o.ToString());
                        var unit = GetUnit(it["govEmployeePositions"][0]["empPosUnitCode"]?.ToString());
                        var employeeCode = it["employeeCode"].ToString();
                        var oCode = it["govEmployeePositions"][0]["organizationCode"]?.ToString();
                        var fullname = GetFullName(oCode);
                        var user = users.Where(x => x.EmployeeCode == it["employeeCode"]?.ToString()).FirstOrDefault();
                        if (user != null)
                        {
                            if (unit.UnitCode == user.UnitCode)
                            {
                                user.IsUpdateUnit = 0;
                            }
                            user.Name = it["employeeName"].ToString();
                            //user.Avatar = it["govEmpAvatar"]?.ToString() ?? "";
                            user.Gender = it["empGender"].ToString().ToInt();
                            user.OrganizationCode = oCode;
                            user.OrganizationName = fullname;
                            user.empJobLevelCode = it["empJobLevelCode"]?.ToString();
                            user.empBudgetedPostCode = it["empBudgetedPostCode"]?.ToString();
                            user.empJobLevelName = ddService.GetPropertyNameByCode("职级", it["empJobLevelCode"]?.ToString());
                            user.empBudgetedPostName = ddService.GetPropertyNameByCode("人员编制", it["empBudgetedPostCode"].ToString());
                            user.orderInOrganization = it["govEmployeePositions"][0]["orderInOrganization"]?.ToString();
                            user.gmtCreate = Convert.ToDateTime(it["gmtCreate"].ToString());
                            user.updateDate = DateTime.Now;
                            user.Status = it["govEmployeePositions"][0]["status"].ToString() == "F" ? 用户状态.已停用 : 用户状态.使用中;
                            ctx.SaveChanges();
                        }
                        else
                        {

                            ctx.Yqd_User.Add(new Yqd_User
                            {
                                AccountId = 0,
                                Openid = "",
                                Roles = "30",
                                PermitItem = "0",
                                EmployeeCode = it["employeeCode"]?.ToString(),
                                Name = it["employeeName"].ToString(),
                                //Avatar = it["govEmpAvatar"]?.ToString() ?? "",
                                Gender = it["empGender"].ToString().ToInt(),
                                OrganizationCode = oCode,
                                OrganizationName = fullname,
                                UnitCode = unit.UnitCode,
                                UnitName = unit.UnitName,
                                empJobLevelCode = it["empJobLevelCode"]?.ToString(),
                                empBudgetedPostCode = it["empBudgetedPostCode"].ToString(),
                                empJobLevelName = ddService.GetPropertyNameByCode("职级", it["empJobLevelCode"]?.ToString()),
                                empBudgetedPostName = ddService.GetPropertyNameByCode("人员编制", it["empBudgetedPostCode"].ToString()),
                                orderInOrganization = it["govEmployeePositions"][0]["orderInOrganization"]?.ToString(),
                                gmtCreate = Convert.ToDateTime(it["gmtCreate"].ToString()),
                                Status = it["govEmployeePositions"][0]["status"].ToString() == "F" ? 用户状态.已停用 : 用户状态.使用中,
                                Instime = DateTime.Now
                            });
                            var re = ctx.SaveChanges();
                        }
                        listEmployee.Add(it["employeeCode"]?.ToString());
                    }
                }
            }

            var inUsers = users.Where(x => !listEmployee.Contains(x.EmployeeCode)).ToList();
            foreach (var item in inUsers)
            {
                item.Status = 用户状态.已停用;
                ctx.SaveChanges();
            }
            var result = listEmployee;

            return this.ToJson(new
            {
                success = true
            });
        }
        private void LoadDepartment(string organizationCode, int tenantId, List<string> arr)
        {
            using (var ctx = new YqdContext())
            {
                var ddService = Fn.GetService<DdService>();
                var data = ddService.pageSubOrganizationCodes(organizationCode, tenantId);
                foreach (var item in data)
                {
                    arr.Add(item.ToString());

                    //if (UpdateDepartment(organizationCode, item, tenantId))
                    //{
                    //}
                    LoadDepartment(item.ToString(), tenantId, arr);

                }
            }
        }

        private bool UpdateDepartment(string ParentCode, string item, int tenantId)
        {
            var info = ddService.GetOrganizationInfo(item, tenantId);
            var isLeaf = ddService.pageSubOrganizationCodes(item, tenantId, true).Count == 0;
            var code = info["institutionLevelCode"]?.ToString() ?? "";
            var organizationCode = info["organizationCode"].ToString();
            var org = ctx.Yqd_Department.SingleOrDefault(it => it.OrganizationCode == organizationCode);
            if (org == null)
            {
                ctx.Yqd_Department.Add(new Yqd_Department
                {
                    OrganizationCode = organizationCode,
                    ParentCode = ParentCode,
                    Name = info["organizationName"].ToString(),
                    InstitutionLevelCode = code,
                    InstitutionLevelName = ddService.GetPropertyNameByCode("单位级别", code),
                    TypeCode = info["typeCode"]?.ToString() ?? "",
                    TypeName = info["typeName"]?.ToString() ?? "",
                    isLeaf = isLeaf

                });
                try
                {
                    int ret = ctx.SaveChanges();
                    if (ret > 0)
                    {
                        var xx = "";
                    }
                }
                catch (Exception ex)
                {
                    string msg = ex.Message;
                }
            }
            else
            {
                org.Name = info["organizationName"].ToString();
                org.InstitutionLevelCode = code;
                org.InstitutionLevelName = ddService.GetPropertyNameByCode("单位级别", code);
                org.TypeCode = info["typeCode"]?.ToString() ?? "";
                org.TypeName = info["typeName"]?.ToString() ?? "";
                org.isLeaf = isLeaf;
                ctx.SaveChanges();
            }

            //var info = ddService.GetOrganizationInfo(organizationCode, tenantId);
            //if (info != null)
            //{
            //    var code = info["institutionLevelCode"]?.ToString() ?? "";
            //    var org = ctx.Yqd_Department.FirstOrDefault(it => it.OrganizationCode == organizationCode);
            //    if (org == null)
            //    {
            //        ctx.Yqd_Department.Add(new Yqd_Department
            //        {
            //            OrganizationCode = organizationCode,
            //            ParentCode = parentCode,
            //            Name = info["organizationName"].ToString(),
            //            InstitutionLevelCode = code,
            //            InstitutionLevelName = ddService.GetPropertyNameByCode("单位级别", code),
            //            TypeCode = info["typeCode"]?.ToString() ?? "",
            //            TypeName = info["typeName"]?.ToString() ?? ""
            //        });
            //        SaveChanges();
            //        return true;
            //    }
            //    //else
            //    //{
            //    //    org.Name = info["organizationName"].ToString();
            //    //    org.InstitutionLevelCode = code;
            //    //    org.InstitutionLevelName = ddService.GetPropertyNameByCode("单位级别", code);
            //    //    org.TypeCode = info["typeCode"]?.ToString() ?? "";
            //    //    org.TypeName = info["typeName"]?.ToString() ?? "";
            //    //}
            //}
            return false;
        }


        private void UpdateEmployee(string organizationCode, int tenantId)
        {
            var arr = ddService.pageOrganizationEmployeePositions(organizationCode, tenantId);
            if (arr != null)
            {
                foreach (var j in arr)
                {
                    var o = JToken.Parse(j.ToString());
                    //var info111 = ddService.GetOrganizationInfo(organizationCode, tenantId);
                    var oCode = o["govEmployeePositions"][0]["organizationCode"]?.ToString();
                    var org = ctx.Yqd_Department.FirstOrDefault(it => it.OrganizationCode == oCode);
                    if (org != null)
                    {
                        var unit = GetUnit(o["govEmployeePositions"][0]["empPosUnitCode"]?.ToString());
                        var employeeCode = o["employeeCode"].ToString();
                        var fullname = GetFullName(oCode);
                        //var info = ddService.GetEmployeeInfo(employeeCode, tenantId);
                        var emp = ctx.Yqd_User.FirstOrDefault(it => it.EmployeeCode == employeeCode);
                        if (emp == null)
                        {
                            try
                            {

                                ctx.Yqd_User.Add(new Yqd_User
                                {
                                    AccountId = 0,
                                    Openid = "",
                                    Roles = "30",
                                    PermitItem = "0",
                                    EmployeeCode = employeeCode,
                                    Name = o["employeeName"].ToString(),
                                    Avatar = o["govEmpAvatar"]?.ToString() ?? "",
                                    Gender = o["empGender"].ToString().ToInt(),
                                    OrganizationCode = oCode,
                                    OrganizationName = fullname,
                                    UnitCode = unit.UnitCode,
                                    UnitName = unit.UnitName,
                                    empJobLevelCode = o["empJobLevelCode"]?.ToString(),
                                    empBudgetedPostCode = o["empBudgetedPostCode"].ToString(),
                                    empJobLevelName = ddService.GetPropertyNameByCode("职级", o["empJobLevelCode"]?.ToString()),
                                    empBudgetedPostName = ddService.GetPropertyNameByCode("人员编制", o["empBudgetedPostCode"].ToString()),
                                    orderInOrganization = o["govEmployeePositions"][0]["orderInOrganization"]?.ToString(),
                                    gmtCreate = Convert.ToDateTime(o["gmtCreate"].ToString()),
                                    Status = o["govEmployeePositions"][0]["status"].ToString() == "F" ? 用户状态.已停用 : 用户状态.使用中,
                                    Instime = DateTime.Now
                                });
                                var re = ctx.SaveChanges();
                            }
                            catch (Exception ex)
                            {

                                throw ex;
                            }
                            //SaveChanges();
                        }
                        else
                        {
                            //if (emp.gmtCreate != null)
                            //{
                            //    continue;
                            //}
                            emp.Name = o["employeeName"].ToString();
                            //emp.Avatar = o["govEmpAvatar"]?.ToString() ?? "";
                            emp.Gender = o["empGender"].ToString().ToInt();
                            emp.OrganizationCode = oCode;
                            emp.OrganizationName = fullname;
                            //emp.UnitCode = unit.UnitCode;
                            //emp.UnitName = unit.UnitName;
                            emp.empJobLevelCode = o["empJobLevelCode"]?.ToString();
                            emp.empBudgetedPostCode = o["empBudgetedPostCode"].ToString();
                            emp.empJobLevelName = ddService.GetPropertyNameByCode("职级", o["empJobLevelCode"]?.ToString());
                            emp.empBudgetedPostName = ddService.GetPropertyNameByCode("人员编制", o["empBudgetedPostCode"].ToString());
                            emp.Status = o["govEmployeePositions"][0]["status"].ToString() == "F" ? 用户状态.已停用 : 用户状态.使用中;
                            emp.gmtCreate = Convert.ToDateTime(o["gmtCreate"].ToString());
                            emp.orderInOrganization = o["govEmployeePositions"][0]["orderInOrganization"]?.ToString();
                            SaveChanges();

                        }
                    }
                }
            }
            //var data = ddService.pageOrganizationEmployeeCodes(organizationCode, tenantId);
            //foreach (var EmployeeCode in data)
            //{
            //    var info = ddService.GetEmployeeInfo(EmployeeCode, tenantId);
            //    var empJobLevelCode = info["empJobLevelCode"]?.ToString() ?? "";
            //    var empBudgetedPostCode = info["empBudgetedPostCode"]?.ToString() ?? "";

            //    var code = info["institutionLevelCode"]?.ToString() ?? "";
            //    var emp = ctx.Yqd_User.FirstOrDefault(it => it.EmployeeCode == EmployeeCode);
            //    if (emp == null)
            //    {
            //        ctx.Yqd_User.Add(new Yqd_User
            //        {
            //            AccountId = 0,
            //            Openid = "",
            //            Roles = "0",
            //            EmployeeCode = EmployeeCode,
            //            Name = info["employeeName"].ToString(),
            //            Avatar = info["govEmpAvatar"]?.ToString() ?? "",
            //            Gender = info["empGender"].ToString().ToInt(),
            //            OrganizationCode = organizationCode,
            //            empJobLevelCode = empJobLevelCode,
            //            empBudgetedPostCode = empBudgetedPostCode,
            //            empJobLevelName = ddService.GetPropertyNameByCode("职级", empJobLevelCode),
            //            empBudgetedPostName = ddService.GetPropertyNameByCode("人员编制", empBudgetedPostCode)
            //        });
            //        SaveChanges();
            //    }
            //    //else
            //    //{
            //    //    emp.Name = info["employeeName"].ToString();
            //    //    emp.Avatar = info["govEmpAvatar"]?.ToString() ?? "";
            //    //    emp.Gender = info["empGender"].ToString().ToInt();
            //    //    emp.OrganizationCode = organizationCode;
            //    //    emp.empJobLevelCode = empJobLevelCode;
            //    //    emp.empBudgetedPostCode = empBudgetedPostCode;
            //    //    emp.empJobLevelName = ddService.GetPropertyNameByCode("职级", empJobLevelCode);
            //    //    emp.empBudgetedPostName = ddService.GetPropertyNameByCode("人员编制", empBudgetedPostCode);
            //    //}
            //}
        }
        private void SaveChanges()
        {
            ctx.SaveChanges();
            if (count++ >= 100)
            {
                count = 0;
                //ctx = new SqmyContext();
            }
        }

        private (string UnitCode, string UnitName) GetUnit(string OrganizationCode)
        {
            var org = ctx.Yqd_Department.FirstOrDefault(it => it.OrganizationCode == OrganizationCode);
            if (org == null)
            {
                return ("", "");
            }
            if (org.TypeCode == "GOV_UNIT")
            {
                var unit = ctx.Yqd_Unit.Where(x => x.OrganizationCode == org.OrganizationCode).FirstOrDefault();
                if (unit != null)
                {
                    UnitCode = unit.UnitCode;
                    UnitName = unit.Name;
                }
                else
                {
                    UnitCode = org.OrganizationCode;
                    UnitName = org.Name;
                }
            }
            if (org.TypeCode == "GOV_HOLLOW_STRIP_NODE")
            {
                return (UnitCode, UnitName);
            }
            return GetUnit(org.ParentCode);
        }
        private string GetFullName(string OrganizationCode)
        {
            List<string> list = new List<string>();
            var org = ctx.Yqd_Department.FirstOrDefault(it => it.OrganizationCode == OrganizationCode);
            if (org == null)
            {
                return "";
            }
            list.Add(org.Name);
            var result = GetParentName(list, org.ParentCode);
            result.Reverse();
            return string.Join(">", result);
        }
        private List<string> GetParentName(List<string> str, string parentOrganizationCode)
        {
            var org = ctx.Yqd_Department.FirstOrDefault(it => it.OrganizationCode == parentOrganizationCode);
            if (org == null)
            {
                return str;
            }
            str.Add(org.Name);

            return GetParentName(str, org.ParentCode);
        }
        private void UpdateConfig(string type, JArray data)
        {
            var ct = tcm.ConfigType.Where(it => it.PlusID == "Yqd" && it.Groupname == "枚举字典" && it.Name == type);
            tcm.ConfigType.RemoveRange(ct);
            var cc = tcm.Config.Where(it => it.PlusID == "Yqd" && it.Groupname == "枚举字典" && it.Name == type);
            tcm.Config.RemoveRange(cc);
            tcm.SaveChanges();
            var id = DAL.MaxID();
            tcm.ConfigType.Add(new Tcm_ConfigType
            {
                ConfigTypeID = id,
                PlusID = "Yqd",
                Name = type,
                Groupname = "枚举字典",
                Locked = false,
                Tactic = id,
                Modtime = DateTime.Now,
                Creator = 1
            });
            tcm.SaveChanges();
            foreach (var item in data)
            {
                var cid = DAL.MaxID();
                tcm.Config.Add(new Tcm_Config
                {
                    ConfigID = cid,
                    ConfigTypeID = id,
                    PlusID = "Yqd",
                    ConfigTypeName = type,
                    Groupname = "枚举字典",
                    Name = item["code"].ToString(),
                    Value = item["name"].ToString(),
                    Locked = false,
                    Tactic = cid,
                    Modtime = DateTime.Now,
                    Creator = 1,
                    Disabled = false
                });
            }
            tcm.SaveChanges();
        }
    }
}
